const express = require("express");
const router = express.Router();
const passport = require("passport");
const Carousel = require("../../../models/Carousel");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// @route  GET api/carousels/test
router.get("/test", (req, res) => res.json({ msg: "carousels works" }));

// @route  POST api/carousels/add
router.post("/add", auth, async (req, res) => {
  try {
    const carousel = await Carousel.create(req.body);
    console.log("添加数据成功:", carousel);
    res.status(200).json({ success: true, data: carousel });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/carousels
router.get("/", auth, async (req, res) => {
  try {
    const carousels = await Carousel.find();
    console.log("获取数据成功:", carousels);
    res
      .status(200)
      .json({ success: true, count: carousels.length, data: carousels });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/carousels/:id
router.get("/:id", auth, async (req, res) => {
  try {
    const carousel = await Carousel.findById(req.params.id);
    if (!carousel) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("获取数据成功", carousel);
    res.status(200).json({ success: true, data: carousel });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  PUT api/carousels/edit
router.put("/edit", auth, async (req, res) => {
  try {
    const { _id, ...updateData } = req.body;
    const carousel = await Carousel.findByIdAndUpdate(_id, updateData, {
      new: true,
    });
    if (!carousel) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("编辑数据成功:", carousel);
    res.status(200).json({ success: true, data: carousel });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/carousels/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const carousel = await Carousel.findByIdAndRemove(_id);
    if (!carousel) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("删除数据成功:", carousel);
    res.status(200).json({ success: true, data: carousel });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
